package com.renwei.yunlong.activity.work;

import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.bean.WorkBean;
import com.renwei.yunlong.event.SendWorkEvent;
import com.renwei.yunlong.fragment.PhotoUpdataFragment;
import com.renwei.yunlong.fragment.SendWorkDetailFragment;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class SendWorkActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.bt_send_work)
    Button btSendWork;
    @Bind(R.id.ll_root)
    LinearLayout llRoot;
    private PhotoUpdataFragment photoUpdataFragment;
    private SendWorkDetailFragment sendWorkDetailFragment;
    private String hardwareId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_work);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);


        hardwareId = getIntent().getStringExtra("hardwareId");
        if (TextUtils.isEmpty(hardwareId)) {
            initAnimation();
        }
        initView();
    }

    private void initAnimation() {
        llRoot.post(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Animator animator = ViewAnimationUtils.createCircularReveal(
                            llRoot,// 操作的视图
                            getIntent().getIntExtra("x", 0), // 动画的中心点X
                            getIntent().getIntExtra("y", 0) + simpleTileView.getHeight(), // 动画的中心点Y
                            getIntent().getIntExtra("start_radius", 0), // 动画半径
                            getIntent().getIntExtra("end_radius", 0)  // 动画结束半径
                    );
                    animator.setInterpolator(new AccelerateInterpolator());
                    animator.setDuration(300);
                    animator.start();
                }
            }
        });
    }

    private void initView() {
        simpleTileView.setTitle("发起工单");
        TextView titleView = simpleTileView.getTitleView();
        Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        titleView.setCompoundDrawables(null, null, titleLeft, null);
        titleView.setCompoundDrawablePadding(10);

        titleView.setOnClickListener(this);
        btSendWork.setOnClickListener(this);


        String[] titles = {"基本信息", "添加附件"};
        List<Fragment> list = new ArrayList<>();
        sendWorkDetailFragment = new SendWorkDetailFragment();
        photoUpdataFragment = new PhotoUpdataFragment();
        list.add(sendWorkDetailFragment);
        list.add(photoUpdataFragment);

        TablayoutAdapter adapter = new TablayoutAdapter(getSupportFragmentManager(), list, titles);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_send_work:
                HashMap<String, String> map = sendWorkDetailFragment.getSendWorkInfo();
                if (map == null || map.size() == 0) {
                    return;
                }
                List<UpdateUserIconBean> photoInfo = photoUpdataFragment.getPhotoInfo();
                // 图片上传
                StringBuilder filenames = new StringBuilder();
                StringBuilder attachPath = new StringBuilder();
                StringBuilder attachSize = new StringBuilder();
                for (int i = 0; i < photoInfo.size(); i++) {
                    UpdateUserIconBean photo = photoInfo.get(i);
                    if (i == photoInfo.size() - 1) {
                        filenames.append(photo.getName());
                        attachPath.append(photo.getPath());
                        attachSize.append(photo.getSize());
                    } else {
                        filenames.append(photo.getName()).append(",");
                        attachPath.append(photo.getPath()).append(",");
                        attachSize.append(photo.getSize()).append(",");
                    }
                }
                map.put("filenames", filenames.toString());
                map.put("attachPath", attachPath.toString());
                map.put("attachSize", attachSize.toString());

                ServiceRequestManager.getManager().sendWorkOrder(this, JsonMapUtil.mapToJson(map), this);
                break;
            case R.id.option_textview_title:
                GuideWebActivity.openActivity(this, Api.$().GUIDE_SEND_WORK_URI);
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        WorkBean ownerWorkBean = new Gson().fromJson(result, WorkBean.class);
        if (ownerWorkBean.getMessage().getCode() == 200) {
            if ("1".equals(ownerWorkBean.getRows().getOverLimit())) {
//                showCenterInfoMsg("本月工单数量超限!");
                showCenterInfoMsg(String.format(getResources().getString(R.string.send_work_fail), ownerWorkBean.getRows().getVersionName(), ownerWorkBean.getRows().getVersionNumber()));
            } else {
                showCenterSuccessMsg("发起成功");
                EventBus.getDefault().post(new SendWorkEvent());
                finish();
            }
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, View view) {
        Intent intent = new Intent(context, SendWorkActivity.class);
        intent.putExtra("x", (int) view.getX() + view.getWidth() / 2);
        intent.putExtra("y", (int) view.getY() - view.getHeight() / 2);
        intent.putExtra("start_radius", view.getWidth() / 2);
        intent.putExtra("end_radius", ((Activity) context).getWindow().getDecorView().getHeight());
        context.startActivity(intent);
    }

    public static void OpenActivity(Context context, String hardwareId, String hardwareName, String companyName, String companyCode,String bindFlag) {
        Intent intent = new Intent(context, SendWorkActivity.class);
        intent.putExtra("hardwareId", hardwareId);
        intent.putExtra("hardwareName", hardwareName);
        intent.putExtra("companyName", companyName);
        intent.putExtra("companyCode", companyCode);
        intent.putExtra("bindFlag", bindFlag);
        context.startActivity(intent);
    }
}
